package com.jingzhe.controller.login;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jingzhe.biz.sys.domain.SysUser;
import com.jingzhe.biz.sys.service.ISysUserService;
import com.jingzhe.controller.login.vo.LoginReqVo;
import com.mysql.jdbc.StringUtils;

/**
 * 登入登录操作
 * @author wanghj
 *
 */
@Controller
public class LoginWeb {
    private final static Logger  logger = LoggerFactory.getLogger(LoginWeb.class);
    
    //登录页面
    private final static String LOGIN_PAGE = "login/login";
    
    //登录后的首页
    private final static String MAIN_PAGE = "login/main";
    
    @Resource
    private ISysUserService sysUserService;
    
    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toLogin() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:/main";
        }
        return LOGIN_PAGE;
    }
    
    /**
     * 登录之后的默认页
     * @return
     */
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String toMain() {
        return MAIN_PAGE;
    }
    
    /**
     * 登录
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@Valid @ModelAttribute("loginReqVo") LoginReqVo loginReqVo, BindingResult br, HttpServletRequest request) {
        logger.debug(loginReqVo.toString());
        
        if(StringUtils.isNullOrEmpty(loginReqVo.getUserName()) 
                || StringUtils.isNullOrEmpty(loginReqVo.getPsd())) {
            request.setAttribute("errorMsg", "用户名或密码不能为空。");
            return LOGIN_PAGE;
        }
                
        if (loginReqVo.getRememberMe() == null) {
            loginReqVo.setRememberMe(false);
        }
        
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginReqVo.getUserName(), loginReqVo.getPsd(), loginReqVo.getRememberMe());
        
        try {
            subject.login(token);
        } catch(UnknownAccountException uae) {
            request.setAttribute("errorMsg", "用户名或密码不正确。");
            return LOGIN_PAGE;
        }catch (IncorrectCredentialsException ice) { 
            request.setAttribute("errorMsg", "用户名或密码不正确。");
            return LOGIN_PAGE;
        } catch (LockedAccountException lae) { 
            request.setAttribute("errorMsg", "该已帐号禁止登录。");
            return LOGIN_PAGE;
        } catch (AuthenticationException ae) { 
            request.setAttribute("errorMsg", "系统异常。");
            logger.error("{} 登录失败。", new Object[]{loginReqVo.getUserName()}, ae);
            return LOGIN_PAGE;
        }
        
        SysUser sysUser = sysUserService.selectByLoginName(loginReqVo.getUserName());
        subject.getSession().setAttribute("userId", sysUser.getId());
        subject.getSession().setAttribute("loginName", loginReqVo.getUserName());
        
        return "redirect:/main";
    }
    
    /**
     * 退出
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) { 
            subject.logout();
        }
        return "redirect:/login";
    }
}
